package com.ken.mqspring.converter;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.support.converter.MessageConversionException;
import org.springframework.amqp.support.converter.MessageConverter;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.UUID;

/**
 * Created by renchongyu on 2018/11/22.
 */
public class PDFMessageConverter implements MessageConverter {

    @Override
    public Message toMessage(Object o, MessageProperties messageProperties) throws MessageConversionException {
        throw new MessageConversionException("PDF MessageConverter error");
    }

    @Override
    public Object fromMessage(Message message) throws MessageConversionException {
        System.out.println("PDF MessageConverter start");

        byte[] body = message.getBody();
        String fileName = UUID.randomUUID().toString();
        String path = "/Users/renchongyu/image/"+fileName+".pdf";
        File file = new File(path);
        try {
            Files.copy(new ByteArrayInputStream(body), file.toPath());
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("PDF MessageConverter end");
        return file;
    }
}
